package com.zerowidth.db.op;

import com.zerowidth.db.DBHelper;
import com.zerowidth.db.base.SqlResult;
import com.zerowidth.db.utils.IOUtils;
import com.zerowidth.db.utils.TimeUtils;

import java.sql.ResultSet;
import java.sql.SQLException;

public class ExchangeRecordDB {

    public static int count(String start_time, String end_time) {
        String sql = String.format("SELECT COUNT(*) FROM exchange_record WHERE create_time >= '%s' " +
                " AND create_time <= '%s'", start_time, end_time);

        return DBHelper.queryCount(sql);
    }


    public static int insert(String oldStatId, String newStatId, String user_id,
                             int vipType, String vipStartTime) {

        String create_time = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_HH_MM_SS);
        String sql = String.format("INSERT INTO exchange_record(old_stat_id, new_stat_id, new_user_id," +
                " vip_type, vip_start_time, create_time) VALUES('%s', '%s', '%s', %d, '%s', '%s')",
                oldStatId, newStatId, user_id, vipType, vipStartTime, create_time);

        return DBHelper.executeInsert(sql);
    }


    public static String findExchangeUserId(String oldStatId) {
        String sql = String.format("SELECT * FROM exchange_record WHERE old_stat_id LIKE '%%%s%%'", oldStatId);

        SqlResult sr = DBHelper.executeQueryEx(sql);

        try {
            if (sr == null) {
                return null;
            }

            ResultSet rs = sr.rs;
            if (rs.next()) {
                return rs.getString("new_user_id");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IOUtils.close(sr);
        }

        return null;
    }


}
